import * as api from './api';
import {
    getCurrentUserPagePermissionsApi,
    getCurrentUserPagePermissionsFail,
    getCurrentUserPagePermissionsSuccess,
} from 'Shared/actions/currentUserContext';
import {PAGE_CODE} from './constants';
import {PAGE} from '../constants';
import {conventTableCondition} from '../utils';

/*==============================初始化API================================= */
//获取初始化数据和权限
export const getInitData = () => dispatch => {
    const permissions = getCurrentUserPagePermissionsApi(PAGE_CODE).then(res => {
        if(res.isOk)
            dispatch(getCurrentUserPagePermissionsSuccess(res.data));
        else
            dispatch(getCurrentUserPagePermissionsFail(res.statusCode, res.message));
        return res.isOk;
    });
    return permissions;
};
/*==============================查询列表================================= */
export const GET_LIST_BEGIN = 'GET_LIST_BEGIN';
export const GET_LIST_SUCCESS = 'GET_LIST_SUCCESS';
export const GET_LIST_FAIL = 'GET_LIST_FAIL';

export const getListBegin = () => ({
    type: GET_LIST_BEGIN,
});
export const getListSuccess = (data, condition) => ({
    type: GET_LIST_SUCCESS,
    data,
    condition,
});
export const getListFail = () => ({
    type: GET_LIST_FAIL
});

//获取列表
export const getList = condition => dispatch => {
    if(!condition)
        return;
    const queryCondition = conventTableCondition(condition);
    dispatch(getListBegin());
    return api.getList(queryCondition).then(res => {
        if(res.ok)
            dispatch(getListSuccess(res.data, condition));
        else
            dispatch(getListFail());
    });
};
//按钮搜索
export const querySearch = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryCondition']).toJS();
    condition.pageIndex = PAGE.index;
    dispatch(getList(condition));
};
//分页排序搜索
export const tableSearch = page => (dispatch, getState) => {
    const query = getState().getIn(['page', 'appState', 'queryBySort']).toJS();
    const condition = Object.assign({}, query, page);
    dispatch(getList(condition));
};

/*=============================获取详情================================== */
export const GET_DETAIL_BEGIN = 'GET_DETAIL_BEGIN';
export const GET_DETAIL_SUCCESS = 'GET_DETAIL_SUCCESS';
export const GET_DETAIL_FAIL = 'GET_DETAIL_FAIL';
export const getDetailBegin = () => ({
    type: GET_DETAIL_BEGIN,
});

export const getDetailSuccess = data => ({
    type: GET_DETAIL_SUCCESS,
    data,
});

const getDetailFail = () => ({
    type: GET_DETAIL_FAIL,
});

//获取详情
export const getDetail = id => dispatch => {
    dispatch(getDetailBegin());
    api.getDetail(id).then(res => {
        if(res.ok)
            dispatch(getDetailSuccess(res.data));
        else
            dispatch(getDetailFail());
    });
};

/*==============================查询action================================= */
export const SAVE_QUERY_CONDITION = 'SAVE_QUERY_CONDITION';
export const saveQueryCondition = (name, value) => ({
    type: SAVE_QUERY_CONDITION,
    name,
    value
});
/*==============================重置查询条件================================= */
export const RESET_QUERY_PANEL = 'RESET_QUERY_PANEL';
export const resetQueryPanel = () => ({
    type: RESET_QUERY_PANEL
});

//关系维护
export const onSubmit = (id, details) => () => {
    const dealerIds = [];
    details.forEach(r => {
        dealerIds.push(r.id);
    });
    return api.modify(id, dealerIds).then(res => ({success: res.ok}));
};

/*=============================查询总代子公司信息信息================================== */
export const GET_DEALERS_BEGIN = 'GET_DEALERS_BEGIN';
export const GET_DEALERS_SUCCESS = 'GET_DEALERS_SUCCESS';
export const GET_DEALERS_FAIL = 'GET_DEALERS_FAIL';

const getDealersBegin = () => ({
    type: GET_DEALERS_BEGIN,
});
const getDealersSuccess = (data, condition) => ({
    type: GET_DEALERS_SUCCESS,
    data,
    condition
});
const getDealersFail = () => ({
    type: GET_DEALERS_FAIL,
});

const getDealers = condition => dispatch => {
    dispatch(getDealersBegin());
    return api.getDealers({
        ...condition
    }).then(res => {
        if(res.ok)
            dispatch(getDealersSuccess(res.data, condition));
        else
            dispatch(getDealersFail());
    });
};

/*=============================查询大区信息================================== */
export const GET_MARKETDEPARTMENTS_BEGIN = 'GET_MARKETDEPARTMENTS_BEGIN';
export const GET_MARKETDEPARTMENTS_SUCCESS = 'GET_MARKETDEPARTMENTS_SUCCESS';
export const GET_MARKETDEPARTMENTS_FAIL = 'GET_MARKETDEPARTMENTS_FAIL';

const getMarketDepartmentsBegin = () => ({
    type: GET_MARKETDEPARTMENTS_BEGIN,
});
const getMarketDepartmentsSuccess = (data, name) => ({
    type: GET_MARKETDEPARTMENTS_SUCCESS,
    data,
    name
});
const getMarketDepartmentsFail = () => ({
    type: GET_MARKETDEPARTMENTS_FAIL,
});

export const getMarketDepartments = name => dispatch => {
    dispatch(getMarketDepartmentsBegin());
    return api.getMarketDepartments({areaName: name}).then(res => {
        if(res.ok)
            dispatch(getMarketDepartmentsSuccess(res.data, name));
        else
            dispatch(getMarketDepartmentsFail());
    });
};

/*=============================查询大区信息================================== */
export const GET_MARKETDEPARTMENTS_TOP_SUCCESS = 'GET_MARKETDEPARTMENTS_TOP_SUCCESS';
const getMarketDepartmentsTopSuccess = data => ({
    type: GET_MARKETDEPARTMENTS_TOP_SUCCESS,
    data,
});

export const getMarketDepartmentsTop = () => (dispatch, getState) => {
    const {data} = getState().getIn(['page', 'domainData', 'marketDepartments']).toJS();
    if(data.length)
        return Promise.resolve(true);
    return api.getRegions().then(res => {
        if(res.ok)
            dispatch(getMarketDepartmentsTopSuccess(res.data));
        else
            dispatch(getMarketDepartmentsFail());
        return res.ok;
    });
};

export const getDealersByCategory = (id, isLeaf) => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryBySortForDealer']).toJS();
    condition.treeId = id;
    condition.isParentNode = !isLeaf;
    condition.pageIndex = PAGE.index;
    if(!condition.pageSize)
        condition.pageSize = PAGE.smallSize;
    return dispatch(getDealers(condition));
};

//分页排序搜索
export const getDealersByPage = page => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryBySortForDealer']).toJS();
    return dispatch(getDealers(Object.assign(condition, page)));
};

// 设置大区id
export const SET_LOCATE = 'SET_LOCATE';
export const setLocateKey = key => ({
    type: SET_LOCATE,
    key,
});

//清除总代子公司信息
export const CLEAR_DEALER = 'CLEAR_DEALER';
export const clearDealer = () => ({
    type: CLEAR_DEALER
});

//修改维修项目查询的条件
export const SAVE_DEALER_CONDITION = 'SAVE_DEALER_CONDITION';
export const saveDealerCondition = (name, value) => ({
    type: SAVE_DEALER_CONDITION,
    name,
    value
});

//按钮搜索
export const getDealersByQuery = () => (dispatch, getState) => {
    const condition = getState().getIn(['page', 'appState', 'queryConditionForDealer']).toJS();
    const {pageSize = PAGE.smallSize, isParentNode, treeId} = getState().getIn(['page', 'appState', 'queryBySortForDealer']).toJS();

    return dispatch(getDealers(Object.assign(condition, {
        pageIndex: PAGE.index,
        pageSize,
        isParentNode,
        treeId
    })));
};
